package com.dtagri.fjwlw.adapter;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import com.dtagri.fjwlw.adapter.viewholders.ViewParser;

/**
 * 通用的Adapter，实现了getCount、getItem等方法,以及封装了getView的逻辑
 * 
 * @author wxjn
 * 
 * @param <T>
 * @param <H>
 */
public abstract class CommonAdapter<T, H extends ViewParser> extends
		BaseAdapter {
	protected Context mContext = null;
	protected List<T> mDataSet = new ArrayList<T>();

	public CommonAdapter(Context context, List<T> mDataSet) {
		this.mContext = context;
		this.mDataSet = mDataSet;
	}

	public int getCount() {
		return mDataSet.size();
	}

	public T getItem(int position) {
		return mDataSet.get(position);
	}

	public long getItemId(int position) {
		return position;
	}

	public void addToFirst(T t) {
		mDataSet.add(0, t);
		notifyDataSetChanged();
	}

	public void addToFirst(List<T> t) {
		mDataSet.addAll(t);
		notifyDataSetChanged();
	}

	public void removeItem(T t) {
		if (t != null) {
			mDataSet.remove(t);
			notifyDataSetChanged();
		}
	}

	public List<T> getDataSource() {
		return mDataSet;
	}

	public void updateListViewData(List<T> lists) {
		mDataSet.clear();
		if (!lists.isEmpty()) {
			mDataSet.addAll(lists);
			notifyDataSetChanged();
		}
	}

	public void addData(T t) {
		if (t != null) {
			mDataSet.add(t);
			notifyDataSetChanged();
		}
	}

	public void addData(List<T> lists) {
		if (!lists.isEmpty()) {
			mDataSet.addAll(lists);
			notifyDataSetChanged();
		}
	}

	public void addDatasOnly(List<T> newDatas) {
		mDataSet.addAll(newDatas);
	}

	@SuppressWarnings("unchecked")
	@Override
	public View getView(int position, View view, ViewGroup parent) {
		if (view == null) {
			view = createViewHolder().inflate(mContext, parent, false);
		}

		H holder = (H) view.getTag();
		setItemData(position, holder, view);
		return view;
	}

	/**
	 * 创建ViewHolder
	 * 
	 * @param view
	 * @param parent
	 * @return
	 */
	protected abstract H createViewHolder();

	/**
	 * 设置每项数据到View上
	 * 
	 * @param position
	 *            Item索引
	 * @param viewHolder
	 *            ViewHolder
	 * @param rootView
	 *            根视图
	 */
	protected abstract void setItemData(int position, H viewHolder,
			View rootView);

}
